package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.demo.common.Result;
import com.example.demo.entity.*;
import com.example.demo.mapper.EmployeeRoleMapper;
import com.example.demo.security.util.JwtUtils;
import com.example.demo.service.BusinessService;
import com.example.demo.service.RoleService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.*;
import io.swagger.annotations.Api;
import org.ini4j.spi.RegEscapeTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;


@Api(tags = "员工管理接口")

@RestController
//@CrossOrigin(origins = "*")
@RequestMapping("/employee")
public class EmployeeController {

    @Resource
    private RoleService roleService;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Resource
    private BusinessService businessService;

    @Resource
    private EmployeeRoleMapper employeeRoleMapper;

    //testOK
//    @ApiOperation(value ="员工登录")
//    @ApiResponses(value={
//            @ApiResponse(code=200, message="成功"),
//            @ApiResponse(code=401, message="用户名或密码错误"),
//            @ApiResponse(code=500, message="服务器错误")
//    })
//    @PostMapping("/login")
//    public Result login(@RequestBody Employee employee){
//        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(employee.getEmployeeName(),employee.getEmployeePassword());
//        Authentication authentication=authenticationManager.authenticate(authenticationToken);
//        if(Objects.isNull(authentication)){
//            throw new RuntimeException("用户名或密码错误");
//        }
//        Result result=new Result();
//        result.setCode("200");
//        result.setMsg("登录成功");
//        LoginUser loginUser=(LoginUser) authentication.getPrincipal();
//        System.out.println(loginUser);
////        loginUser.setRole(employeeMapper.selectRoleById(loginUser.getId()));
//        Map<String,String> payload=new HashMap<>();
//        payload.put("id",loginUser.getId().toString());
//        payload.put("name",loginUser.getUsername());
//        String token= JwtUtils.createToken(payload);
//        result.setToken(token);
//        result.setData(loginUser);
//        return result;
//    }

    //testOK
    @ApiOperation(value="添加员工角色", notes="根据员工ID和角色ID进行员工角色添加")
    @ApiImplicitParam(name = "roleId", value = "角色ID", required = true, dataType = "int", paramType = "query")
    @ApiResponses(value={
            @ApiResponse(code=200, message="添加员工角色成功"),
            @ApiResponse(code=401, message="添加员工角色失败"),
            @ApiResponse(code=500, message="服务器错误")
    })
    @PostMapping ("addEmployeeRole")
    public Result addEmployeeRole(Integer employeeId, Integer roleId){
        int res = roleService.addEmployeeRole(employeeId, roleId);
        if(res != 0){
            return Result.success("添加员工角色成功");
        }else{
            return Result.error("401","添加员工角色失败");
        }
    }

    //testOK
    @ApiOperation(value="删除员工角色")
    @ApiResponses(value={
            @ApiResponse(code=200, message="删除员工角色成功"),
            @ApiResponse(code=401, message="删除员工角色失败"),
            @ApiResponse(code=500, message="服务器错误")
    })
    @DeleteMapping("delEmployeeRole")
    public Result delEmployeeRole(Integer employeeId){
        int res = roleService.delEmployeeRole(employeeId);
        if(res != 0){
            return Result.success("删除员工角色成功");
        }else{
            return Result.error("401","删除员工角色失败");
        }
    }

    @PreAuthorize("hasAuthority('sys:employee:get')")
    @ApiOperation(value="获取员工列表",notes = "根据商家ID获取员工列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="businessId",value = "商家ID", required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "name", value = "员工名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "role", value = "角色名称", dataType = "String", paramType = "query"),
    })

    @ApiResponses(value={
            @ApiResponse(code=200, message="获取员工列表成功"),
            @ApiResponse(code=401, message="获取员工列表失败"),
            @ApiResponse(code=500, message="服务器错误")
    })
    @GetMapping("/getEmployeesByBusinessId")
    public PageInfo<EmployeeVo> getEmployeesByBusinessId(Integer businessId,String name,String role,
                                                       @RequestParam(defaultValue = "1") int current,
                                                       @RequestParam(defaultValue = "10") int size){
        List<EmployeeVo> employeeVoList=roleService.selectEmployeesByBusinessId(businessId);

        if (!name.isEmpty()||!role.isEmpty()) {
            current = 1;
        }
        Predicate<EmployeeVo> predicate;
        if(!role.isEmpty()){
            predicate= employeeVo -> employeeVo.getEmployeeName().contains(name)
                    &&employeeVo.getRoles().contains(role);
        }else{
            predicate = employeeVo -> employeeVo.getEmployeeName().contains(name);
        }


        List<EmployeeVo> result = employeeVoList.stream()
                .filter(predicate)
                .collect(Collectors.toList());

        List<EmployeeVo> pageList = result.stream()
                .skip((current - 1) * size) // 跳过前面的记录
                .limit(size) // 取出指定数量的记录
                .collect(Collectors.toList()); // 将结果转换为列表
        PageInfo<EmployeeVo> pageInfo = new PageInfo<>(pageList); // 构造 PageInfo 对象
        long total = result.size();
        pageInfo. setTotal(total);
        return pageInfo;
    }

    @PreAuthorize("hasAuthority('sys:employee:del')")
    @ApiOperation(value="删除员工信息",notes = "根据员工ID删除员工信息")
    @ApiImplicitParam(name = "ids", value = "员工ID数组", required = true, dataType = "MyArray", paramType = "body")
    @ApiResponses(value={
            @ApiResponse(code=200, message="删除员工信息成功"),
            @ApiResponse(code=401, message="删除员工信息失败"),
            @ApiResponse(code=500, message="服务器错误")
    })
    @DeleteMapping("/delEmployee")
    public Result delEmployee(@RequestBody MyArray ids){

        int res = businessService.delEmployee(ids);
        if(res == 1){
            return Result.success("删除员工信息成功");
        }else {
            return Result.error("400","删除员工信息失败");
        }
    }


    //@PreAuthorize("hasAuthority('sys:employee:get')")
    @ApiOperation(value="通过ID获取员工信息",notes = "根据员工ID获取员工信息")
    @ApiImplicitParam(name="employeeId",value = "员工ID", required = true,dataType = "int",paramType = "query")
    @ApiResponses(value={
            @ApiResponse(code=200, message="获取员工信息成功"),
            @ApiResponse(code=401, message="获取员工信息失败"),
            @ApiResponse(code=500, message="服务器错误")
    })
    @GetMapping("/getEmployeeByEmployeeId")
    public Result getEmployeeByEmployeeId(Integer employeeId){
        EmployeeVo employeeVo=roleService.selectEmployeeByEmployeeId(employeeId);
        if(employeeVo!=null){
            return Result.success(employeeVo);
        }else{
            return Result.error("401","获取员工信息失败");
        }
    }


    @PreAuthorize("hasAuthority('sys:employee:edit')")
    @ApiOperation(value="修改员工信息",notes = "修改员工信息以及员工角色")
    @ApiImplicitParam(name="roleId",value = "角色ID", required = true,dataType = "int",paramType = "query")
    @ApiResponses(value={
            @ApiResponse(code=200, message="修改员工信息成功"),
            @ApiResponse(code=401, message="修改员工信息失败"),
            @ApiResponse(code=500, message="服务器错误")
    })
    @PostMapping("/updateEmployee")
    public Result updateEmployee(@RequestBody Employee employee,Integer roleId){
        try {
            roleService.updateEmployee(employee);
            EmployeeRole employeeRole=new EmployeeRole(employee.getEmployeeId(), roleId);
            UpdateWrapper<EmployeeRole> updateWrapper=new UpdateWrapper();
            updateWrapper.eq("employee_id",employeeRole.getEmployeeId());
            employeeRoleMapper.update(employeeRole,updateWrapper);
            return Result.success("修改成功");
        }catch (Exception e){
            return Result.error("401","修改失败");
        }
    }


    @PreAuthorize("hasAuthority('sys:employee:add')")
    @ApiOperation(value="添加员工",notes = "添加员工信息")
    @ApiResponses(value={
            @ApiResponse(code=200, message="添加成功"),
            @ApiResponse(code=401, message="添加失败"),
            @ApiResponse(code=500, message="服务器错误")
    })@PostMapping("/addEmployee")
    public Result addEmployee(@RequestBody Employee employee){
        Integer res=roleService.addEmployee(employee);
        if(res==1){
            return Result.success("添加员工成功");
        }else{
            return Result.error("401","添加失败");
        }
    }


}
